import React, { useState, useEffect } from 'react'
import { useWebSocket } from '../hooks/useWebSocket'
import { useKafkaTopics } from '../hooks/useKafkaTopics'
import { useTopicPartitions } from '../hooks/useTopicPartitions'
import { useKafkaStore } from '../stores/kafkaStore'
import { kafkaApi } from '../services/kafka'
import { ModeSelector } from '../components/MessageProducer/ModeSelector'
import { SingleMessageForm } from '../components/MessageProducer/SingleMessageForm'
import { BatchMessageForm } from '../components/MessageProducer/BatchMessageForm'
import DataGeneratorPanel from '../components/MessageProducer/DataGeneratorPanel'
import { ProducerSidebar } from '../components/MessageProducer/ProducerSidebar'

export interface ProducerMessage {
  key: string
  value: string
  headers?: Record<string, string>
  partition?: number
  format?: string
}

export interface ProducerResult {
  success: boolean
  message?: string
  partition?: number
  offset?: number
  timestamp?: number
  error?: string
}

export default function MessageProducer() {
  const [mode, setMode] = useState<'single' | 'batch' | 'generator'>('single')
  const [selectedTopic, setSelectedTopic] = useState<string>('')
  const [lastResult, setLastResult] = useState<ProducerResult | null>(null)
  const [isProducing, setIsProducing] = useState(false)
  const [initializing, setInitializing] = useState(true)

  const { connected } = useWebSocket()
  const { topics, loading: topicsLoading, loadTopics } = useKafkaTopics()
  const {
    partitions,
    partitionDetails,
    loading: partitionsLoading,
    loadPartitions
  } = useTopicPartitions()
  const { setConnectionStatus, isConnected } = useKafkaStore()

  // 当WebSocket连接建立时加载Topics
  useEffect(() => {
    if (connected) {
      setConnectionStatus('已连接', true)
      loadTopics()
    } else {
      setConnectionStatus('未连接', false)
    }
  }, [connected, setConnectionStatus, loadTopics])

  // 当选择的Topic变化时，加载分区信息
  useEffect(() => {
    if (selectedTopic) {
      loadPartitions(selectedTopic)
    }
  }, [selectedTopic, loadPartitions])

  // 初始化延迟，避免闪烁
  useEffect(() => {
    const timer = setTimeout(() => setInitializing(false), 800)
    return () => clearTimeout(timer)
  }, [])

  const handleProduceMessage = async (message: ProducerMessage) => {
    if (!selectedTopic) {
      setLastResult({
        success: false,
        error: '请先选择Topic'
      })
      return
    }

    setIsProducing(true)
    try {
      const response = await fetch('/api/producer/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          topic: selectedTopic,
          key: message.key,
          value: message.value,
          headers: message.headers,
          partition: message.partition,
          message_format: message.format || 'json'
        }),
      })

      const result = await response.json()
      
      if (response.ok) {
        setLastResult({
          success: true,
          message: '消息发送成功',
          partition: result.partition,
          offset: result.offset,
          timestamp: result.timestamp
        })
      } else {
        setLastResult({
          success: false,
          error: result.detail || '发送失败'
        })
      }
    } catch (error) {
      setLastResult({
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      })
    } finally {
      setIsProducing(false)
    }
  }

  const handleBatchProduce = async (messages: ProducerMessage[]) => {
    if (!selectedTopic) {
      setLastResult({
        success: false,
        error: '请先选择Topic'
      })
      return
    }

    setIsProducing(true)
    try {
      const response = await fetch('/api/producer/send-batch', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          topic: selectedTopic,
          messages: messages.map(msg => ({
            key: msg.key,
            value: msg.value,
            headers: msg.headers,
            partition: msg.partition,
            message_format: msg.format || 'json'
          })),
          message_format: messages[0]?.format || 'json'  // 使用第一个消息的格式作为默认值
        }),
      })

      const result = await response.json()
      
      if (response.ok) {
        setLastResult({
          success: true,
          message: `批量发送成功，共 ${messages.length} 条消息`
        })
      } else {
        setLastResult({
          success: false,
          error: result.detail || '批量发送失败'
        })
      }
    } catch (error) {
      setLastResult({
        success: false,
        error: error instanceof Error ? error.message : '网络错误'
      })
    } finally {
      setIsProducing(false)
    }
  }

  // 处理Topic变化的包装函数
  const handleTopicChange = (topic: string | null) => {
    if (topic) {
      setSelectedTopic(topic)
    }
  }

  if (topicsLoading || initializing) {
    return (
      <div className="space-y-8">
        <div className="card">
          <div className="card-content text-center py-16">
            <div className="inline-block animate-spin rounded-full h-16 w-16 border-4 border-primary-200 border-t-primary-600"></div>
            <p className="mt-6 text-lg text-gray-600 font-medium">
              {initializing ? '初始化消息生产器...' : '加载Topic列表...'}
            </p>
            <p className="mt-2 text-sm text-gray-500">
              {initializing ? '正在检测Kafka连接状态' : '正在获取可用的Kafka Topic'}
            </p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* 页面标题 */}
      <div className="text-center lg:text-left">
        <h1 className="text-3xl font-bold gradient-text mb-2">消息生产</h1>
        <p className="text-lg text-gray-600">发送单条或批量消息到Kafka Topic</p>
      </div>

      {/* 模式切换 */}
      <ModeSelector
        mode={mode}
        onModeChange={setMode}
      />

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
        {/* 主要内容区域 */}
        <div className="xl:col-span-2">
          {mode === 'single' ? (
            <SingleMessageForm
              topics={topics}
              selectedTopic={selectedTopic}
              partitions={partitions}
              partitionsLoading={partitionsLoading}
              onTopicChange={handleTopicChange}
              onProduceMessage={handleProduceMessage}
              isProducing={isProducing}
            />
          ) : mode === 'batch' ? (
            <BatchMessageForm
              topics={topics}
              selectedTopic={selectedTopic}
              partitions={partitions}
              partitionsLoading={partitionsLoading}
              onTopicChange={handleTopicChange}
              onBatchProduce={handleBatchProduce}
              isProducing={isProducing}
            />
          ) : (
            <DataGeneratorPanel
              topics={topics}
              selectedTopic={selectedTopic}
              onTopicChange={handleTopicChange}
              onProgress={(progress) => {
                // 可以在这里处理进度更新
                console.log('数据生成进度:', progress)
              }}
            />
          )}
        </div>

        {/* 侧边栏 */}
        <div className="space-y-6">
          <ProducerSidebar
            lastResult={lastResult}
            connected={connected}
            selectedTopic={selectedTopic}
            isProducing={isProducing}
          />
        </div>
      </div>
    </div>
  )
}
